import React, { useState, useEffect, useRef } from 'react';
import { Button, Form, Input, Table, Tabs, InputNumber, message } from 'antd';
import { connect, useIntl } from 'umi';
import MyDataTable from '@/components/MyDataTable';
import { VendorSelect, CustSelect } from '@/components/FormItemSelect';
import request from '@/utils/request';

const { TabPane } = Tabs;

const ViewPage = (props: any) => {
  const [dataSource, setDataSource] = useState([]);
  const [records, setRecords] = useState([]);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    if (props.data) {
      let dataSource: any = [];
      let sumCost: number = 0;
      props.data.forEach((element: any) => {
        let obj = {
          partTranId: element.Id,
          partNum: element.PartNum,
          lineDesc: element.PartDescription,
          quantity: element.TranQty < 0 ? -element.TranQty : element.TranQty,
          ium: element.UM,
          unitCost: element.MtlUnitCost,
          extCost: element.ExtCost < 0 ? -element.ExtCost : element.ExtCost,
        };
        sumCost += obj.extCost;
        dataSource.push(obj);
      });
      setDataSource(dataSource);
      let firstD = props.data[0];
      let datas = {
        vendorNum: firstD.vendorNum,
        custNum: firstD.custNum,
        amount: sumCost,
        invoiceType: props.invoiceType,
      };
      formRef.current.setFieldsValue(datas);
    }
  }, [props.data, props.invoiceType]);

  const onFinish = (values: any) => {
    request('/api/services/app/Invoice/CreateInvoice', {
      method: 'POST',
      data: {
        node: values,
        items: dataSource,
      },
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({ id: 'pages.create.success' }));
        }
      }
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const doubleClick = (record: any) => {
    console.log(record);
  };

  const setRowSelection = (items: any) => {
    setRecords(items)
  };

  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.invoiceNum' }),
      dataIndex: 'invoiceNum',
    },
    {
      title: intl.formatMessage({ id: 'pages.invoiceLine' }),
      dataIndex: 'invoiceLine',
      width: 60,
    },
    {
      title: intl.formatMessage({ id: 'pages.partNum' }),
      dataIndex: 'partNum',
    },
    {
      title: intl.formatMessage({ id: 'pages.lineDesc' }),
      dataIndex: 'lineDesc',
      ellipsis: true,
    },
    {
      title: intl.formatMessage({ id: 'pages.quantity' }),
      dataIndex: 'quantity',
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'pages.taxCost' }),
      dataIndex: 'taxCost',
      width: 60,
    },
    {
      title: intl.formatMessage({ id: 'pages.unitCost' }),
      dataIndex: 'unitCost',
      width: 100,
    },
    {
      title: intl.formatMessage({ id: 'pages.extCost' }),
      dataIndex: 'extCost',
      width: 100,
    },
  ];
  const columns2 = [
    {
      title: intl.formatMessage({ id: 'pages.partNum' }),
      dataIndex: 'partNum',
    },
    {
      title: intl.formatMessage({ id: 'pages.lineDesc' }),
      dataIndex: 'lineDesc',
      ellipsis: true,
    },
    {
      title: intl.formatMessage({ id: 'pages.quantity' }),
      dataIndex: 'quantity',
    },
    {
      title: intl.formatMessage({ id: 'pages.IUM' }),
      dataIndex: 'ium',
    },
    {
      title: intl.formatMessage({ id: 'pages.unitCost' }),
      dataIndex: 'unitCost',
    },
    {
      title: intl.formatMessage({ id: 'pages.extCost' }),
      dataIndex: 'extCost',
    },
  ];

  return (
    <>
      <Tabs defaultActiveKey="1">
        <TabPane tab={intl.formatMessage({ id: 'pages.details' })} key="1">
          <Form
            ref={formRef}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 16 }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            <Form.Item
              label={intl.formatMessage({ id: 'pages.invoiceNum' })}
              name="invoiceNum"
              rules={[{ required: true, message: intl.formatMessage({ id: 'pages.invoiceNum.required' }) }]}
            >
              <Input />
            </Form.Item>
            <Form.Item label={intl.formatMessage({ id: 'pages.invoiceType' })} name="invoiceType" hidden>
              <Input />
            </Form.Item>
            <VendorSelect
              rules={[{ required: true, message: intl.formatMessage({ id: 'pages.vendor.required' }) }]}
              showSearch={true}
              width={200}
              name="vendorNum"
              label={intl.formatMessage({ id: 'pages.vendor' })}
              hidden={props.invoiceType == 'INV'}
            />
            <CustSelect
              rules={[{ required: true, message: intl.formatMessage({ id: 'pages.customer.required' }) }]}
              showSearch={true}
              width={200}
              name="custNum"
              label={intl.formatMessage({ id: 'pages.customer' })}
              hidden={props.invoiceType == 'ONV'}
            />
            <Form.Item label={intl.formatMessage({ id: 'pages.amount' })} name="amount">
              <InputNumber disabled />
            </Form.Item>
            <Form.Item label={intl.formatMessage({ id: 'pages.commentText' })} name="commentText">
              <Input.TextArea />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
              <Button type="primary" htmlType="submit">
                {intl.formatMessage({ id: 'pages.submit' })}
              </Button>
            </Form.Item>
          </Form>
          <Table
            rowKey="partTranId"
            size="small"
            columns={columns2}
            dataSource={dataSource}
            pagination={false}
            bordered
          />
        </TabPane>
        <TabPane tab={intl.formatMessage({ id: 'pages.allInvoices' })} key="2">
          <MyDataTable
            act="GetList"
            columns={columns}
            showRefresh
            pageSize={10}
            control="Invoice"
            doubleClick={doubleClick}
            rowSelection={(items: any) => setRowSelection(items)}
          ></MyDataTable>
        </TabPane>
      </Tabs>
    </>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
}))(ViewPage);
